﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="EntryDetails.xaml.cs" company="Mar3ek">
//   This code is licensed under the Mozilla Public License 2.0.
//   You can find the full license text at the following address:
//   https://winkee.codeplex.com/license
// </copyright>
// <summary>
//   An empty page that can be used on its own or navigated to within a Frame.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace WinKee.Pages
{
    using System;
    using System.ComponentModel;
    using System.Runtime.CompilerServices;
    using System.Windows.Input;

    using Windows.UI.Popups;
    using Windows.UI.Xaml.Controls;
    using Windows.UI.Xaml.Navigation;

    using WinKee.Common;
    using WinKee.Controls;
    using WinKee.Models;

    /// <summary>
    /// The entry details page.
    /// </summary>
    public sealed partial class EntryDetails : INotifyPropertyChanged
    {
        #region Fields

        /// <summary>
        /// The navigation helper.
        /// </summary>
        private readonly NavigationHelper navigationHelper;

        /// <summary>
        /// The entry.
        /// </summary>
        private PasswordEntry entry;

        #endregion

        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="EntryDetails"/> class.
        /// </summary>
        public EntryDetails()
        {
            this.InitializeComponent();

            this.navigationHelper = new NavigationHelper(this);
            this.navigationHelper.LoadState += this.NavigationHelperLoadState;
            this.navigationHelper.SaveState += this.NavigationHelperSaveState;

            this.CopyUsernameCommand = new RelayCommand(this.CopyUsernameAction);
            this.CopyPasswordCommand = new RelayCommand(this.CopyPasswordAction);
            this.ShowWarningCommand = new RelayCommand(this.ShowWarningAction);
        }

        private async void ShowWarningAction()
        {
            var loader = new Windows.ApplicationModel.Resources.ResourceLoader();
            var str = loader.GetString("TaskManagerSecurityWarning");
            var dialog = new MessageDialog(str);
            await dialog.ShowAsync();
        }

        #endregion

        #region Public Events

        /// <summary>
        /// The property changed.
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

        #region Public Properties

        /// <summary>
        /// Gets the <see cref="NavigationHelper"/> associated with this <see cref="Page"/>.
        /// </summary>
        public NavigationHelper NavigationHelper
        {
            get
            {
                return this.navigationHelper;
            }
        }

        /// <summary>
        /// Gets or sets the entry.
        /// </summary>
        public PasswordEntry Entry
        {
            get
            {
                return this.entry;
            }

            set
            {
                this.entry = value;
                this.OnPropertyChanged();
            }
        }

        /// <summary>
        /// Gets the copy username command.
        /// </summary>
        public ICommand CopyUsernameCommand { get; private set; }

        /// <summary>
        /// Gets the copy password command.
        /// </summary>
        public ICommand CopyPasswordCommand { get; private set; }

        public ICommand ShowWarningCommand { get; private set; }

        #endregion

        #region Methods

        /// <summary>
        /// The on navigated from.
        /// </summary>
        /// <param name="e">
        /// The event arguments.
        /// </param>
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            this.navigationHelper.OnNavigatedFrom(e);
        }

        /// <summary>
        /// The methods provided in this section are simply used to allow
        /// NavigationHelper to respond to the page's navigation methods.
        /// <para>
        /// Page specific logic should be placed in event handlers for the  
        /// <see cref="NavigationHelper.LoadState"/>
        /// and <see cref="NavigationHelper.SaveState"/>.
        /// The navigation parameter is available in the LoadState method 
        /// in addition to page state preserved during an earlier session.
        /// </para>
        /// </summary>
        /// <param name="e">
        /// Provides data for navigation methods and event
        /// handlers that cannot cancel the navigation request.
        /// </param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            this.navigationHelper.OnNavigatedTo(e);
        }

        /// <summary>
        /// Selects the password.
        /// </summary>
        private void CopyPasswordAction()
        {
            this.EntryHub.ScrollToSection(this.EntryHub.Sections[0]);
            if (MainEntrySection.Instance != null)
            {
                MainEntrySection.Instance.SelectPassword();
            }
        }

        /// <summary>
        /// Selects the username.
        /// </summary>
        private void CopyUsernameAction()
        {
            this.EntryHub.ScrollToSection(this.EntryHub.Sections[0]);
            if (MainEntrySection.Instance != null)
            {
                MainEntrySection.Instance.SelectUsername();
            }
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="sender">
        /// The source of the event; typically <see cref="NavigationHelper"/>
        /// </param>
        /// <param name="e">
        /// Event data that provides both the navigation parameter passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
        /// a dictionary of state preserved by this page during an earlier
        /// session.  The state will be null the first time a page is visited.
        /// </param>
        private async void NavigationHelperLoadState(object sender, LoadStateEventArgs e)
        {
            var serialized = e.NavigationParameter as string;
            if (string.IsNullOrEmpty(serialized))
            {
                var md = new MessageDialog("No entry provided to display. Going back.");
                await md.ShowAsync();
                this.Frame.Navigate(typeof(MainPage));
                return;
            }

            var en = serialized.Deserialize<PasswordEntry>();

            this.Entry = en;
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="sender">
        /// The source of the event; typically <see cref="NavigationHelper"/>
        /// </param>
        /// <param name="e">
        /// Event data that provides an empty dictionary to be populated with
        /// serializable state.
        /// </param>
        private void NavigationHelperSaveState(object sender, SaveStateEventArgs e)
        {
        }

        /// <summary>
        /// The on property changed.
        /// </summary>
        /// <param name="propertyName">
        /// The property name.
        /// </param>
        private void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            var handler = this.PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        #endregion
    }
}